package com.aquila.bible.activity;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.aquila.bible.MyBaseActivity;
import com.aquila.bible.R;
import com.aquila.bible.SearchResultObject;
import com.aquila.bible.system.SystemConfig;
import com.aquila.bible.utils.TextReader;

public class SearchActivity extends MyBaseActivity implements OnClickListener{
	final String tag = "Search" ;
	private Button backButton ;
	private EditText editText ;
	private Button searckButton ;
	private Spinner spinner ;
	private ListView resultListView ;
	private ResultAdapter adapter ;
	
	private String searchBoundStrings[] ;
	private String searchBoundIndex[] ;
	
	private ArrayAdapter<String> arrayAdapter ;
	private int searchMode = 0 ;
	
	private SearchThread thread ;
	private ArrayList<SearchResultObject> arrayList = new ArrayList<SearchResultObject>();
	private Dialog loadingDialog ;
	private LinearLayout processLayout ;
	private int searchResultCount ;
	private int resultCount = 200 ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_layout) ;
		backButton = (Button) findViewById(R.id.btn_search_back) ;
		searckButton = (Button) findViewById(R.id.btn_search_action) ;
		editText = (EditText) findViewById(R.id.et_search) ;
		spinner = (Spinner) findViewById(R.id.spinner_area) ;
		resultListView = (ListView) findViewById(R.id.lv_search_result) ;
		searchBoundStrings = getResources().getStringArray(R.array.search_bound) ;
		searchBoundIndex = getResources().getStringArray(R.array.search_bound_index) ;
		processLayout = (LinearLayout) layoutInflater.inflate(R.layout.process_view, null) ;
		
		loadingDialog = new Dialog(context, R.style.my_dialog) ;
		loadingDialog.setContentView(processLayout) ;
		loadingDialog.setCanceledOnTouchOutside(false) ;
		
		
		arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, searchBoundStrings) ;
		arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) ;
		spinner.setAdapter(arrayAdapter) ;
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				searchMode = arg2 ;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		}) ;
		
		adapter = new ResultAdapter() ;
		resultListView.setAdapter(adapter) ;
		resultListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				
				Intent intent = new Intent() ;
				intent.setClass(context, TextByListActivity.class) ;
				SearchResultObject object = arrayList.get(position) ;
				Bundle bundle = new Bundle() ;
				bundle.putSerializable("object", object) ;
				intent.putExtras(bundle) ;
				startActivity(intent) ;
				
			}
		}) ;
		
		
		backButton.setOnClickListener(this) ;
		searckButton.setOnClickListener(this) ;
		
	}
	
	
	
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				adapter.notifyDataSetChanged() ;
				handler.sendEmptyMessageDelayed(1, 100) ;
			}
			else if (msg.what == 2) {
				adapter.notifyDataSetChanged() ;
				handler.removeMessages(1) ;
				if (loadingDialog.isShowing()) {
					loadingDialog.dismiss() ;
				}
				if (arrayList.size() == 0) {
					showToast("没有搜索到您查找的结果，请检查您的输入是否正确，或者修改搜索条件", false) ;
				}
			}
			else if (msg.what == 3) {
				showToast("最多只能显示"+resultCount+"条搜索结果，如未能满足，请修改搜索范围重新搜索", true) ;
				if (loadingDialog.isShowing()) {
					loadingDialog.dismiss() ;
				}
			}
		};
	} ;
	
	
	
	/**
	 * 搜索方法入口
	 * @param bound
	 * @param keyWords
	 *2012-7-31 下午2:41:51
	 */
	private void searchSection(int bound, String keyWords){
		arrayList.clear() ;
		searchResultCount = 0 ;
		String str = searchBoundIndex[bound] ;
		String[] indexStrings = str.split("_") ;
		int index[] = new int[indexStrings.length];
		int i = 0 ;
		while (i < indexStrings.length) {
			index[i] = Integer.parseInt(indexStrings[i]) ;
			i++ ;
		}
		handler.sendEmptyMessage(1) ;
		
		int j = index[0];
		while(j <= index[1]){
			if (searchResultCount >= resultCount) {
				handler.sendEmptyMessage(3) ;
				return ;
//				break ;
			}
			for (int k = 1, len = Integer.parseInt(SystemConfig.testamentchapterCount[j-1]); k <= len; k++) {
				getSearchResult(keyWords, j, k) ;
			}
			j++ ;
		}
		handler.sendEmptyMessage(2) ;
		
		str = null ;
		indexStrings = null ;
		System.gc() ;
	}
	
	/**
	 * 获取每章的搜索结果
	 * @param keywords
	 * @param bookIndex
	 * @param chapter
	 *2012-7-31 下午2:42:05
	 */
	private void getSearchResult(String keywords, int bookIndex, int chapter){
		String content = TextReader.readChapter(context, bookIndex, chapter) ;
		String[] sections = content.split("\n") ;
		for (int i = 0, len = sections.length; i < len; i++) {
			if (sections[i].contains(keywords)) {
				if (searchResultCount >= resultCount) {
					break ;
				}
				searchResultCount++ ;
				SearchResultObject object = new SearchResultObject() ;
				object.setBookIndex(bookIndex) ;
				object.setBookShortString(SystemConfig.testamentShortStrings[bookIndex-1]) ;
				object.setBookString(SystemConfig.testamentNameStrings[bookIndex-1]) ;
				object.setChapterCount(Integer.parseInt(SystemConfig.testamentchapterCount[bookIndex-1])) ;
				object.setSectionCount(sections.length) ;
				object.setChapterIndex(chapter) ;
				object.setContentString(sections[i]) ;
				object.setKeyWords(keywords) ;
				object.setSectionIndex(i) ;
				arrayList.add(object) ;
			}
		}
//		content = null ;
//		sections = null ;
//		System.gc() ;
	}
	
	
	@Override
	public void onClick(View v) {
		
		if (v == backButton) {
			onBackPressed() ;
		}
		
		else if (v == searckButton) {
			final String keyWords = editText.getText().toString() ;
			if (keyWords == null || keyWords.length() == 0) {
				showToast("请输入搜索关键字", false) ;
				return ;
			}
			else if (!keyWords.matches("[\u4e00-\u9fa5]*")) {
				showToast("您输入的格式不正确，只能输入文字搜索", false) ;
				return ;
			}
			
			if (thread != null && thread.isAlive()) {
				showToast("后台正在处理搜索", false) ;
			}
			else {
				thread = new SearchThread(keyWords) ;
				thread.start() ;
				loadingDialog.show() ;
			}
		}
	}
	
	@Override
	public void onBackPressed() {
		finish() ;
		overridePendingTransition(R.anim.translate_in_from_left, R.anim.translate_out_to_right) ;
	}
	
	
	
	class SearchThread extends Thread{
		String keyWord ;
		public SearchThread(String keyWord){
			this.keyWord = keyWord ;
		}
		
		@Override
		public void run() {
			searchSection(searchMode, keyWord) ;
		}
	}
	
	
	
	
	
	
	
	
	class ResultAdapter extends BaseAdapter{
		LayoutParams params ;
		public ResultAdapter() {
			params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT) ;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return arrayList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		Pattern pattern  ;
		
		
		@Override
		public View getView(int position, View arg1, ViewGroup arg2) {
			LinearLayout layout = (LinearLayout) layoutInflater.inflate(R.layout.search_result_item_layout, null) ;
//			TextView sectionNumTextView = (TextView) layout.findViewById(R.id.tv_chapter_num) ;
			TextView sectionContentTextView = (TextView) layout.findViewById(R.id.tv_search_result_text) ;
//			sectionNumTextView.setVisibility(View.GONE) ;
			SearchResultObject object = arrayList.get(position % arrayList.size()) ;
			
			String temp = object.getContentString() ;
			
			pattern = Pattern.compile(SystemConfig.regex) ;
			Matcher matcher = pattern.matcher(temp) ;
			String val = null ;
			String content ;
			int len = 0  ;
			if (matcher.find()) {
				val = matcher.group() ;
				len = val.length() ;
				if (position == 0) { //去掉首行多空一格字符
					len++ ;
				}
			}
			content = temp.substring(len+1).replace(object.getKeyWords(), "<font color=#11ca41>" + object.getKeyWords() + "</font>") ;
			String displayString = "<b><font color=#ff0000>"+ (position + 1) +" </font>" +"、"+
					"<font color=#1111bb>"+object.getBookShortString() + val +" </font></b>" + content ;
			
			sectionContentTextView.setText(Html.fromHtml(displayString)) ;
			
			return layout;
		}
		
	}
	
	
	

	
	
	
}
